package com.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.web.response.Response;
import com.web.util.FileUtil;
import com.web.util.WebContextUtil;

import jni.PhotoStyling_JAPI;

//处理跨域问题
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class PicController {
	
	//produces 响应的类型和编码，解决响应的中文乱码
	@RequestMapping(value="/uploadPhoto",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
	public @ResponseBody String pic(@RequestParam ("photo") MultipartFile  photo) {
		List<String> retList = new ArrayList<>(); 
		if(photo == null) {
			return new Gson().toJson(new Response().failure("上传失败，图片为空"));
		}
		
		//获取文件名
	    String fileName = photo.getOriginalFilename();
	    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//System.out.println(fileName);
//System.out.println(suffix);

		HttpServletRequest request = WebContextUtil.getRequest();
		String imgPath = "/pic/";
		String path = request.getServletContext().getRealPath(imgPath);	
//System.out.println(path);

		try {
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String newFileName = uuid + "." + suffix;
			FileUtil.saveFileFromInputSream(photo.getInputStream(), path, newFileName);
			PhotoStyling_JAPI pApi = new PhotoStyling_JAPI();
			String[] outPath = new String[5];
			pApi.ps_transImage(path, newFileName, outPath);
			retList.add(imgPath + newFileName);
			for(String name: outPath) {
				//System.out.println(name);
				int pathIndex = name.lastIndexOf(imgPath);
				//System.out.println(pathIndex);
				System.out.println(name.substring(pathIndex, name.length()));
				retList.add(name.substring(pathIndex, name.length()));
			}
		} catch (IOException e) {
			e.printStackTrace();
			return new Gson().toJson(new Response().failure("图片转化失败"));
		}
	    
		return new Gson().toJson(new Response().success(retList));
	}

}
